<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>学生端</title>
    <meta charset="UTF-8">
    <script src="/sockjs.min.js"></script>
    <script src="/stomp.min.js"></script>
    <script src="/jquery.min.js"></script>
</head>
<body>
<h1>Say hello!</h1>
<form id="nameForm">
    <input type="text" id="name" autocomplete="off"/><br/>
    <button>Send</button>
</form>
<ul id="greetings"></ul>
<script>
    var stompClient = null;

    function setConnected(connected) {
        $("#nameForm").toggle(connected);
        $("#greetings").html("");
    }

    function connect() {
        var socket = new SockJS('/ws');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            setConnected(true);
            stompClient.subscribe('/topic/greetings', function (greeting) {
                showGreeting(JSON.parse(greeting.body).content);
            });
        });
    }

    function disconnect() {
        if (stompClient !== null) {
            stompClient.disconnect();
        }
        setConnected(false);
    }

    function sendName() {
        stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
    }

    function showGreeting(message) {
        $("#greetings").append("<li>" + message + "</li>");
    }

    $(function () {
        $("form").on('submit', function (e) {
            e.preventDefault();
        });
        connect();
        $("#nameForm").on('submit', sendName);
    });
</script>
</body>
</html>